from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import images

import model, utils
from config import *

import urllib

class HomePage(webapp.RequestHandler):
    def get(self):
        token = utils.csrf_check(self.request, self.response, force = False)
        # should list all series
        self.response.out.write(utils.render(
            self.request,
            'template/index.html',
            token = token
        ))

    def post(self):
        # should allow an admin to add series
        self.redirect('./%s' % series.short_name)

class UserSignup(webapp.RequestHandler):
    def get(self):
        # registers/updates the user to the service
        us = utils.signup(self.request)
        utils.set_user(us, self.response)
        if self.request.get('continue'):
            self.redirect('./.%s' % self.request.get('continue'))
        else:
            self.redirect('/')

class UserProfile(webapp.RequestHandler):
    def get(self, kn):
        # shows the user's submissions and votes
        user = model.User.get_by_key_name(kn)
        self.response.out.write(template.render('template/user-profile.html',{
            'user': user,
        }))

class ImageDownload(webapp.RequestHandler):
    def get(self, kn, width, height):
        # downloads the image.
        k = db.Key(kn)
        m = model.UploadedImage.get(k)
        if not m:
            return
        self.response.headers['Content-Disposition'] = 'inline;filename="%s"' % urllib.quote(m.caption)
        if m.type in ('image/png','image/jpeg','image/bmp','image/gif','image/tiff'):
            raw_image = m.data
            height = int(height or 0)
            width  = int(width  or 0)
            if height or width:
                image = images.Image(raw_image)
                if not height:
                    height = width
                if not width:
                    width = height
                width  = min(max(width , 25), 1600)
                height = min(max(height, 25), 1600)
                u_ratio = width/height
                o_ratio = image.width/image.height
                if u_ratio > o_ratio:
                    # crop top/bottom
                    image.resize(width=width)
                    ratio = (1.0*image.width*height)/(1.0*width*image.height)
                    image.crop(0.0, 0.5 - ratio/2, 1.0, 0.5 + ratio/2)
                else:
                    # crop left/right
                    image.resize(height=height)
                    ratio = (1.0*width*image.height)/(1.0*image.width*height)
                    image.crop(0.5 - ratio/2, 0.0, 0.5 + ratio/2, 1.0)
                raw_image = image.execute_transforms()
                self.response.headers['Content-Type'] = 'image/png'
            else:
                self.response.headers['Content-Type'] = m.type
            self.response.headers['Cache-Control'] = 'public'
            self.response.headers['Expires'] = 'Sat, 17 Sep 2099 00:34:00 GMT'
            self.response.out.write(raw_image)

class SeriesHome(webapp.RequestHandler):
    def get(self, series_name):
        token = utils.csrf_check(self.request, self.response, force = False)
        # should list all contest in the series
        self.response.out.write(
            utils.render(
                self.request,
                'template/series-home.html',
                series_name,
                token = token
            )
        )
    def post(self, series_name):
        # should allow a @ehn user to add a contest
        self.redirect('./%s' % contest.short_name)

class ContestHome(webapp.RequestHandler):
    def get(self, series_name, contest_name):
        token = utils.csrf_check(self.request, self.response, force = False)
        # should list all submissions in the contest
        self.response.out.write(
            utils.render(
                self.request,
                'template/contest-home.html',
                series_name,
                contest_name,
                token = token
            )
        )
    def post(self, series_name, contest_name):
        token = utils.csrf_check(self.request, self.response)
        submission = utils.put_submission(self.request, series_name, contest_name)
        self.redirect('./%s' % submission.short_name)

class ContestSubmission(webapp.RequestHandler):
    def get(self, series_name, contest_name, submission_name):
        token = utils.csrf_check(self.request, self.response, force = False)
        # should list all votes in the submission
        self.response.out.write(
            utils.render(
                self.request,
                'template/submission-home.html',
                series_name,
                contest_name,
                submission_name,
                token = token
            )
        )
    def post(self, series_name, contest_name, submission_name):
        utils.csrf_check(self.request, self.response)
        # should allow the user to add a vote, or edit a submission
        if self.request.get('action') == 'vote':
            vote = utils.new_vote(self.request, series_name, contest_name, submission_name)
            self.redirect('./%s' % vote.submission.short_name)
        else:
            submission = utils.put_submission(self.request, series_name, contest_name, submission_name)
            self.redirect('./%s' % submission.short_name)

application = webapp.WSGIApplication([
                                        ('/', HomePage),
                                        ('/u', UserSignup),
                                        ('/u/(.*)', UserProfile),
                                        ('/i/(.*?)(?:/(\d+)/(\d+))?', ImageDownload),
                                        ('/([^/]+)/', SeriesHome),
                                        ('/([^/]+)/([^/]+)/', ContestHome),
                                        ('/([^/]+)/([^/]+)/([^/]+)', ContestSubmission)
                                    ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()